package concurrent;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeTest {

    private String name;

    public static void main(String[] args) throws NoSuchFieldException {

        Unsafe unsafe = reflectGetUnsafe();
        assert unsafe != null;
        Field field = UnsafeTest.class.getDeclaredField("name");
        long fieldOffset = unsafe.objectFieldOffset(field);
        System.out.println(fieldOffset);

        UnsafeTest unsafeTest = new UnsafeTest();
        unsafe.compareAndSwapObject(unsafeTest, fieldOffset, null, "涂有");
        System.out.println(unsafeTest.name);
    }

    private static Unsafe reflectGetUnsafe() {
//        return Unsafe.getUnsafe() //报错java.lang.SecurityException: Unsafe
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            return (Unsafe) field.get(null);
        } catch (Exception e) {
            return null;
        }
    }
}
